import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import getPageTitle from '@/utils/get-page-title';
import { message as Message } from '@/utils/resetMessage';
NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start();

  // 设置页面标题
  document.title = getPageTitle(to.meta.title);

  // 是否有token 有默认登陆
  const hasToken = !!store.getters.token;
  console.log('token存在', hasToken);

  if (hasToken) {
    if (to.path === '/login') {
      console.log('有token去/login');
      next();
      return;
    }

    // 判断是否刷新页面
    // vuex中无数据，则为刷新页面
    if (store.state.permission.addRoutes.length === 0) {
      console.log('刷新进入，重新获取路由');
      store
        .dispatch('permission/generateRoutes')
        .then(() => {
          next({ path: to.path });
        })
        .catch(() => {
          console.error('异常：获取用户菜单未空');
          Message.error('异常：获取用户菜单未空');
          next();
        });
    } else {
      next();
    }
  } else {
    // 没登陆
    console.log('未登录，想要前往:', to.path);
    if (to.path === '/login') {
      next();
    } else {
      next({ path: '/login' });
      // bug!!! 从登陆页跳回登陆页 不触发afterEach() 解决进度条问题
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
